/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package com.dc.gameserver.extComponents.nettyEngine4;


import com.dc.gameserver.baseConfig.Config;
import com.dc.gameserver.extComponents.utilsKit.ThreadUtils.PriorityThreadFactory;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;

/**
 * @author :石头哥哥<br/>
 *         Project:CreazyGameServer1.6
 *         Date: 13-3-29
 *         Time: 上午9:53
 *
 *         netty底层处理工具类              流量统计
 *
 */
public class ServerUtil {
    public static final Logger logger =
            LoggerFactory.getLogger(ServerUtil.class);
    private static final long base = currentTimeMillis();


    //global count    1 线程池
    public static final EventExecutorGroup globalTrafficShapingHandlerExecutorGroup= new DefaultEventExecutorGroup(1, new PriorityThreadFactory("executionLogicHandlerThread", Thread.NORM_PRIORITY ));

    //global count
    public static final GlobalTrafficShapingHandler globalTrafficShapingHandler=
            new GlobalTrafficShapingHandler(globalTrafficShapingHandlerExecutorGroup, Config.DEFAULT_VALUE.SERVER_VALUE.checkInterval);


    //     负责处理业务逻辑线程池组         一个线程池中有
    private static EventExecutorGroup[]executorRoomGroups;
    private static int index=0;

//    /**
//     * 初始化线程池组
//     *       DispatcherGroupNum：线程池组大小；
//     *       DispatcherThreads：每个线程池线程数量
//     */
//    @Deprecated
//    public static void init(){
//        executorRoomGroups=new EventExecutorGroup[NServerConfig.DispatcherGroupNum];
//        for (int i=0;i!= NServerConfig.DispatcherGroupNum;++i) {
//            executorRoomGroups[i]= new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors(),
//                    new PriorityThreadFactory("@+数据分发逻辑线程池+#"+i, Thread.NORM_PRIORITY ));
//        }
//        //注册jvm钩子
//        Thread hook=new Thread(){
//            @Override
//            public void run() {
//                super.run();
//                for (EventExecutorGroup executor:executorRoomGroups){
//                    executor.shutdownGracefully();
//                }
//            }
//        };
//        Runtime.getRuntime().addShutdownHook(hook); //add hook
//    }

//    /**
//     * 获取下一个线程池
//     * @return                     EventExecutorGroup
//     */
//    @Deprecated
//    public static EventExecutorGroup NextDispatcherEventExecutor(){
//        index++;
//        if (index== NServerConfig.DispatcherGroupNum)index=0;
//        return executorRoomGroups[index];
//    }

    /**
     *单个连接流量统计
     * @return       ChannelTrafficShapingHandler
     */
    public static ChannelTrafficShapingHandler getChannelTrafficShapingHandler(){
        return new ChannelTrafficShapingHandler(Config.DEFAULT_VALUE.SERVER_VALUE.checkInterval);
    }

    /**
     * all
     *启动流量监控器
     */
    public static void startMonitor(){
        globalTrafficShapingHandler.trafficCounter().start();
    }

    /**
     * all
     * 停止流量监控器
     */
    public static void stopMonitor(){
        globalTrafficShapingHandler.trafficCounter().stop();
    }

    /**
     * all
     * 重置流量统计周期
     * @param newcheckInterval
     */
    public static void configure(long newcheckInterval){
        globalTrafficShapingHandler.trafficCounter().configure(newcheckInterval);
    }


    /**
     *  all
     *  返回在interval周期中读取流量的统计
     *  @return the Read Throughput in KB/s computes in the last check interval
     */
    public static long ReadThroughput(){
        return  (globalTrafficShapingHandler.trafficCounter().lastReadThroughput()>>10);
    }


    /**
     *  all
     *  返回在interval周期中读取流量的统计
     *  @return the Read Throughput in KB/s computes in the last check interval
     */
    public static long WriteThroughput(){
        return  (globalTrafficShapingHandler.trafficCounter().lastWriteThroughput()>>10);
    }

    public static void relaseResorce(){
        globalTrafficShapingHandler.release();
    }

    /**
     * 获取线程名
     * @return
     */
    public static String getThreadName(){
        return Thread.currentThread().getName();
    }

    public static String stamp() {
        return format("%s:%s - ", currentTimeMillis() - base, Thread.currentThread().getName());
    }

}
